package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;
import static java.time.LocalDateTime.now;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {

        //1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            //2.如果不符合，重新提交手机号
            return Result.fail("格式有误，请重新提交手机号！");
        }

        //3.符合则生成验证码
        String code = RandomUtil.randomNumbers(6);

        //TODO 4.保存验证码到redis
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);

        //5.发送验证码
        log.info(code);

        //6.发送成功，返回
        return Result.ok("发送成功！");
    }

    @Override
    public Result userLogin(LoginFormDTO loginForm, HttpSession session) throws JsonProcessingException {

        //1.校验手机号
        String loginFormPhone = loginForm.getPhone();
        String loginFormCode = loginForm.getCode();
        String key = LOGIN_CODE_KEY + loginFormPhone;
        if(RegexUtils.isPhoneInvalid(loginFormPhone)){
            return Result.fail("手机号格式有误，请重新提交手机号！");
        }

        // 2.校验验证码,这里key是手机号，相当于校验了手机号配对验证码（防止别的手机也能登录的情况）
        String code = stringRedisTemplate.opsForValue().get(key);
        if(loginFormCode == null || !loginFormCode.equals(code)){
            //结果不符合，则提示验证码有误
            return Result.fail("验证码有误，请重新输入！");
        }

        //TODO 3.校验成功（这里应该将验证码失效，防止复用），判断是登录还是注册
        stringRedisTemplate.delete(key);

        //查询是否存在该用户
        User user = query().eq("phone", loginFormPhone).one();

        //4.如果不存在则为注册，创建新用户
        if(user == null){
            String nickName = USER_NICK_NAME_PREFIX + RandomUtil.randomString(10);
            user = new User(null, loginFormPhone, null, nickName, null, LocalDateTime.now(), LocalDateTime.now());
            save(user);
        }

        // 6.保存登录信息到redis
        // 6.1生成随机token(UUID)
        String token = UUID.randomUUID(true).toString();
        String tokenKey = LOGIN_USER_KEY + token;

        // 6.2将user对象转为map
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
            CopyOptions.create()
                .setIgnoreNullValue(true)
                    .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));

        // 6.3将userMap存储到redis中
        stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);

        // 6.4设置有效期
        stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);

        //7.返回tokenKey至前端
        return Result.ok(tokenKey);
    }
}
